{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "8cb4192a",
   "metadata": {},
   "source": [
    "## 函数\n",
    "\n",
    "函数是能够实现特定功能的计算机代码，是一种特定的代码组结构\n",
    "\n",
    "代码块+封装\n",
    "\n",
    "函数的作用：\n",
    "    1. 提升代码的重复利用率，避免重复开发相同代码\n",
    "    2. 提高程序开发效率\n",
    "    3. 便于程序维护\n",
    "\n",
    "函数的定义格式\n",
    "\n",
    "函数文档\n",
    "\n",
    "局部变量和全局变量\n",
    "\n",
    "函数的其他使用"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "631bf2c6",
   "metadata": {},
   "source": [
    "### 定义函数\n",
    "\n",
    "以 def 关键词开头，后面接函数名称和圆括号(),由:结束\n",
    "\n",
    "任何传入参数和自变量必须在圆括号里\n",
    "\n",
    "return 结束函数，返回函数结果\n",
    "\n",
    "调用函数： 函数名()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "380c45b9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "very good\n",
      "nice\n",
      "hey\n"
     ]
    }
   ],
   "source": [
    "# 基本函数格式\n",
    "# 函数名称不使用中文，不能以数字开头，可以使用_\n",
    "def fun1():\n",
    "    print('very good')\n",
    "    print('nice')\n",
    "    print('hey')\n",
    "    return     \n",
    "\n",
    "# 调用函数\n",
    "fun1()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "5e8959c0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n",
      "5\n"
     ]
    }
   ],
   "source": [
    "# 带有参数的函数格式\n",
    "# 乘法\n",
    "def fun1(a,b,c,d):\n",
    "    c=a+b\n",
    "    print(c)\n",
    "    return c\n",
    "\n",
    "\n",
    "# 调用函数，需要传参数\n",
    "result=fun1(2,3,4,5)\n",
    "print(result)\n",
    "\n",
    "# 形参： 形式上的参数，声明/定义函数时（）中的参数\n",
    "# 实参： 实际上的参数，调用函数时()中的参数\n",
    "# 注意： 实参将值传递给形参的过程本质上就是简单的变量赋值\n",
    "# 参数必须以正确的顺序传入函数，调用时的数量必须和声明时的一样"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "80f4e413",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-03-10T04:11:06.732034Z",
     "start_time": "2022-03-10T04:11:06.706927Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "姓名：male,年龄:20,性别：july\n"
     ]
    }
   ],
   "source": [
    "# 带有默认值的参数\n",
    "def fun1(name='May',age=18,sex='female'):\n",
    "    print('姓名：{},年龄:{},性别：{}'.format(name,age,sex))\n",
    "    return\n",
    "\n",
    "fun1(sex='male',age=20,name='july')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "id": "4705d75e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 用关键字调用函数，防止参数传错\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "83e7e446",
   "metadata": {},
   "source": [
    "参数个数不确定，`*arg`, `**arg`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "4a49422b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1, 2, 3, 'ji')\n"
     ]
    }
   ],
   "source": [
    "# *arg表示收集任意多个无名参数，类型为tuple收集参数 (用*arg 可以传很多参数)\n",
    "# 为非关键字收集参数\n",
    "\n",
    "def fun2(*arg):\n",
    "    print(arg)\n",
    "    \n",
    "# 以元组(tuple)的方式传入参数\n",
    "fun2(1,2,3,'ji')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "b8ee5d9b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "55\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "55"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Exercise: 计算不确定数字之和\n",
    "def mysum(*args):\n",
    "    total=0\n",
    "    for i in args:\n",
    "        total += i #total=total+i\n",
    "    print(total)\n",
    "    return total\n",
    "\n",
    "mysum(1,2,3,4,5,6,7,8,9,10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "15b0c85f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'a': 1, 'b': 2, 'c': 3}\n"
     ]
    }
   ],
   "source": [
    "# **kargs表示收集关键字参数（带有默认值的参数），为dict，\n",
    "def fun1(**kargs):\n",
    "    print(kargs)\n",
    "\n",
    "\n",
    "fun1(a=1,b=2,c=3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "a62f8bea",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "(2, 3, 'ty')\n",
      "{'c': 2, 'n': 10}\n"
     ]
    }
   ],
   "source": [
    "# 使用时需将*arg放在**arg之前，\n",
    "# 否则会有“Invalid Syntax”的语法错误。\n",
    "# 此外arg与kargs均可以换成其他名字\n",
    "\n",
    "def test(value1,*arg, **kargs):\n",
    "    print(value1)\n",
    "    print(arg)\n",
    "    print(kargs)\n",
    "    \n",
    "test(1,2,3,'ty',c=2,n=10)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "015d7108",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 混合函数\n",
    "\n",
    "def fun5(a,b,name='june',*arg,**kargs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "id": "b58a8f0f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1275\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "1275"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Exercise: 定义一个计算数值累加的函数\n",
    "\n",
    "def mysum(num):\n",
    "    total=0\n",
    "    for i in range(1,num+1):\n",
    "        total += i\n",
    "    print(total)\n",
    "    return total\n",
    "\n",
    "mysum(50)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9c2d84a6",
   "metadata": {},
   "source": [
    "### 函数文档\n",
    "\n",
    "三个单引号或三个双引号加说明"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "e828820f",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "def mysum(num):\n",
    "    '''\n",
    "    这是一个计算加总的函数\n",
    "    参数是int类型\n",
    "    返回值是int类型\n",
    "    '''\n",
    "    pass\n",
    " "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "d6536615",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on function mysum in module __main__:\n",
      "\n",
      "mysum(num)\n",
      "    这是一个计算加总的函数\n",
      "    参数是int类型\n",
      "    返回值是int类型\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(mysum)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "755a5946",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'\\n    这是一个计算加总的函数\\n    参数是int类型\\n    返回值是int类型\\n    '"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "mysum.__doc__"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "e9543cd5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on built-in function max in module builtins:\n",
      "\n",
      "max(...)\n",
      "    max(iterable, *[, default=obj, key=func]) -> value\n",
      "    max(arg1, arg2, *args, *[, key=func]) -> value\n",
      "    \n",
      "    With a single iterable argument, return its biggest item. The\n",
      "    default keyword-only argument specifies an object to return if\n",
      "    the provided iterable is empty.\n",
      "    With two or more arguments, return the largest argument.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(max)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3004201a",
   "metadata": {},
   "source": [
    "### 局部变量 & 全局变量\n",
    "\n",
    "定义在函数内的变量拥有一个局部作用域， 定义在函数外的拥有全局作用域\n",
    "\n",
    "局部变量只能在其被声明的函数内部访问，而全局变量可以在整个程序范围内访问。 调用函数时，所有在函数内声明的变量名称都将被加入到作用域中。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "0e4fbef1",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-03-10T04:19:37.606053Z",
     "start_time": "2022-03-10T04:19:37.588103Z"
    }
   },
   "outputs": [],
   "source": [
    "#函数外定义的称为全局变量\n",
    "name='june'\n",
    "def fun(str1, int1):\n",
    "    #global name  # 声明是全局变量\n",
    "    name = str1\n",
    "    print(name)    \n",
    "    age= int1 # 局部变量\n",
    "    print(age)\n",
    "    return"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "b6b97faf",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-03-10T04:19:38.648539Z",
     "start_time": "2022-03-10T04:19:38.626598Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hey\n",
      "18\n",
      "------------\n",
      "june\n",
      "---------\n"
     ]
    },
    {
     "ename": "NameError",
     "evalue": "name 'age' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[1;32m~\\AppData\\Local\\Temp/ipykernel_18672/2059154782.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m      3\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mname\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      4\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'---------'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 5\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mage\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mNameError\u001b[0m: name 'age' is not defined"
     ]
    }
   ],
   "source": [
    "fun('hey',18)\n",
    "print('------------')\n",
    "print(name)\n",
    "print('---------')\n",
    "print(age)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "4dfee83b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ice\n",
      "-----------\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'ice'"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Python中定义函数时，若想在函数内部对函数外的变量进行操作，\n",
    "# 就需要在函数内部声明其为global\n",
    "\n",
    "name='june'\n",
    "def fun():\n",
    "    global name\n",
    "    name='ice'\n",
    "    print(name)\n",
    "    return\n",
    "fun()\n",
    "print('-----------')\n",
    "name\n",
    "\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "001d85d5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n",
      "2\n"
     ]
    }
   ],
   "source": [
    "a=1 # 在函数内部修改a的值\n",
    "def fun():\n",
    "    global a\n",
    "    a=a+1\n",
    "    print(a)\n",
    "    return \n",
    "\n",
    "fun()\n",
    "print(a)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "cd4c9d83",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<function fun at 0x0000022542046950>\n",
      "3\n"
     ]
    }
   ],
   "source": [
    "\n",
    "fun2=fun\n",
    "print(fun2)\n",
    "fun2()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "644ce838",
   "metadata": {},
   "outputs": [],
   "source": [
    "# NOTE: 函数的自变量可以为函数\n",
    "def fun(a,b,f):\n",
    "    return f(a)+f(b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "id": "7fb00b5a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "11"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fun(1,-10,abs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1bce5ae6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# NOTE: 函数内部也可以内嵌函数\n",
    "def fun(a,b,c):\n",
    "    def sub_fun1(d,c):\n",
    "        pass\n",
    "    def sub_fun2(a,e):\n",
    "        pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "id": "305941e6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 56,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# NOTE: 函数可以return 多个变量\n",
    "def fun(a,b):\n",
    "    return a,b,a+b\n",
    "\n",
    "n=fun(1,10)[0]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "472b1028",
   "metadata": {},
   "source": [
    "### 列表表达式\n",
    "\n",
    "[expression for iter_val in iterable]\n",
    "\n",
    "[expression for iter_val in iterable if cond_expr]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "id": "c70c9936",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['x=A', 'y=B', 'z=C']\n"
     ]
    }
   ],
   "source": [
    "# 快速将 dict 转换为 list\n",
    "# 例如： d={'x':'A','y':'B','z':'C'} 转换为：['x=A','y=B','z=C']\n",
    "d={'x':'A','y':'B','z':'C'}\n",
    "result=[]\n",
    "for key,value in d.items():\n",
    "    result.append('{}={}'.format(key,value))\n",
    "    \n",
    "print(result)    \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "id": "e2b6237e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['x=A', 'y=B', 'z=C']"
      ]
     },
     "execution_count": 59,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "['{}={}'.format(key,value) for key,value in d.items()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "id": "106d5a33",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
      ]
     },
     "execution_count": 63,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 生成list, [1,2,3,4,...,10], list(range(1,11))  range生成的是一个对象\n",
    "[i for i in range(1,11)] "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "id": "63bd505c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]"
      ]
     },
     "execution_count": 64,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 生成[1*1,2*2,...]\n",
    "[i*i for i in range(1,11)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "id": "b0ae882d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3']"
      ]
     },
     "execution_count": 65,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#'abc','123'，想让 a 和 1,2,3 每个字符生成新的字符串，b,c也是\n",
    "a='abc'\n",
    "b='123'\n",
    "\n",
    "new_list=[]\n",
    "for i in a:\n",
    "    for j in b:\n",
    "        new_list.append(i+j)\n",
    "new_list\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "id": "f52e16bc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3']"
      ]
     },
     "execution_count": 66,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "[i+j for i in a for j in b]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "id": "23f5489f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('a', '1'), ('b', '2'), ('c', '3')]"
      ]
     },
     "execution_count": 73,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "c"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 74,
   "id": "3aab49c2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[('a', 'b', 'c'), ('1', '2', '3')]"
      ]
     },
     "execution_count": 74,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "list(zip(*c))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "id": "04dc1a84",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a 1\n",
      "b 2\n",
      "c 3\n"
     ]
    }
   ],
   "source": [
    "for i,j in zip(a,b):\n",
    "    print(i,j)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "id": "fd524d94",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['a1', 'b2', 'c3']"
      ]
     },
     "execution_count": 70,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "[i+j for i,j in zip(a,b)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "id": "6224fd99",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['a1', 'a2', 'a3', 'c1', 'c2', 'c3']"
      ]
     },
     "execution_count": 76,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 列表表达式中加条件\n",
    "a='abc'\n",
    "b='123'\n",
    "[i+j for i in a for j in b if i!='b']\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 78,
   "id": "c68f99a2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[7, 8, 9, 1, 2, 3, 4, 5, 6]"
      ]
     },
     "execution_count": 78,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# c = [[7,8,9],[1,2,3],[4,5,6]]  转为 [7, 8, 9, 1, 2, 3, 4, 5, 6]\n",
    "c = [[7,8,9],[1,2,3],[4,5,6]] \n",
    "\n",
    "[i for b in c for i in b ]        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 80,
   "id": "c4dda2c2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3.141592653589793\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "['3.1', '3.14', '3.142', '3.1416', '3.14159']"
      ]
     },
     "execution_count": 80,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from math import pi\n",
    "print(pi)\n",
    "[str(round(pi, i)) for i in range(1, 6)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "id": "e1777ea6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a': '1', 'b': '2', 'c': '3'}"
      ]
     },
     "execution_count": 81,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 列表表达式也可用于生成dict\n",
    "a='abc'\n",
    "b='123'\n",
    "{k:v for k,v in zip(a,b)}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "id": "4774cb33",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1*1=1  \n",
      "1*2=2  2*2=4  \n",
      "1*3=3  2*3=6  3*3=9  \n",
      "1*4=4  2*4=8  3*4=12 4*4=16 \n",
      "1*5=5  2*5=10 3*5=15 4*5=20 5*5=25 \n",
      "1*6=6  2*6=12 3*6=18 4*6=24 5*6=30 6*6=36 \n",
      "1*7=7  2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49 \n",
      "1*8=8  2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64 \n",
      "1*9=9  2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81 \n"
     ]
    }
   ],
   "source": [
    "# 练习：打印9*9乘法表\n",
    "#print('\\n'.join([''.join(['%s*%s=%-2s '%(y,x,x*y)for y in range(1,x+1)])for x in range(1,10)]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 91,
   "id": "62cd3697",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1*9=9  2*9=18  3*9=27  4*9=36  5*9=45  6*9=54  7*9=63  8*9=72  9*9=81\n"
     ]
    }
   ],
   "source": [
    "row=9\n",
    "a='  '.join(['{}*{}={}'.format(col,row,col*row) for col in range(1,row+1)])\n",
    "print(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 97,
   "id": "c2d021ea",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1*1=1\n",
      "1*2=2 2*2=4\n",
      "1*3=3 2*3=6 3*3=9\n",
      "1*4=4 2*4=8 3*4=12 4*4=16\n",
      "1*5=5 2*5=10 3*5=15 4*5=20 5*5=25\n",
      "1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36\n",
      "1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49\n",
      "1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64\n",
      "1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81\n"
     ]
    }
   ],
   "source": [
    "a2='\\n'.join([' '.join(['{}*{}={}'.format(col,row,col*row) for col in range(1,row+1)]) for row in range(1,10)])\n",
    "print(a2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 94,
   "id": "b2512042",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['1*1=1', '1*2=2 2*2=4', '1*3=3 2*3=6 3*3=9', '1*4=4 2*4=8 3*4=12 4*4=16', '1*5=5 2*5=10 3*5=15 4*5=20 5*5=25', '1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36', '1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49', '1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64', '1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81']\n"
     ]
    }
   ],
   "source": [
    "print(a2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 96,
   "id": "1f615792",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1*1=1\n",
      "1*2=2 2*2=4\n",
      "1*3=3 2*3=6 3*3=9\n",
      "1*4=4 2*4=8 3*4=12 4*4=16\n",
      "1*5=5 2*5=10 3*5=15 4*5=20 5*5=25\n",
      "1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36\n",
      "1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49\n",
      "1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64\n",
      "1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81\n"
     ]
    }
   ],
   "source": [
    "print('\\n'.join(a2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 87,
   "id": "47d21d4c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'a11,a12,a14'"
      ]
     },
     "execution_count": 87,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a=['a11','a12','a14']\n",
    "#'a11,a12,a14'\n",
    "','.join(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 102,
   "id": "3437be61",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Green'"
      ]
     },
     "execution_count": 102,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a=0\n",
    "b='Red' if a>0 else 'Green'\n",
    "b"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "21438ff5",
   "metadata": {},
   "source": [
    "### 匿名函数\n",
    "\n",
    "lambda 创建匿名函数,可以减少函数名称冲突\n",
    "\n",
    "lambda 主体是一个表达式，只能写一行，而不是代码块，仅仅能在lambda表达式中封装有限的逻辑进去\n",
    "\n",
    "lambda 函数拥有自己的命名空间，且不能访问自己参数列表之外或全局命名空间里的参数"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "21c6d5b3",
   "metadata": {},
   "source": [
    "在Python中，lambda的语法是唯一的。其形式如下：\n",
    "\n",
    "lambda argument_list: expression\n",
    "\n",
    "其中，lambda是Python预留的关键字，\n",
    "\n",
    "argument_list和expression由用户自定义。\n",
    "\n",
    "expression是一个关于参数的表达式。表达式中出现的参数需要在argument_list中有定义，并且表达式只能是单行的。\n",
    "\n",
    "lambda argument_list: expression表示的是一个函数。这个函数叫做lambda函数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 103,
   "id": "57caf790",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "8"
      ]
     },
     "execution_count": 103,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 将lambda函数赋值给一个变量，通过这个变量间接调用该lambda函数。\n",
    "\n",
    "g=lambda a,b:a*b\n",
    "g(2,4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 104,
   "id": "f6b05f8f",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6"
      ]
     },
     "execution_count": 104,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fun = lambda v1,v2: v1+v2\n",
    "fun(2,4)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "37cfb21d",
   "metadata": {},
   "source": [
    "### 一些内置函数"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9a1c8c6c",
   "metadata": {},
   "source": [
    "#### 数学函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "4a326c55",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "10"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 绝对值\n",
    "abs(-10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "f286e3fb",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 最大值 max，最小值 min\n",
    "max([1,2,3,4])\n",
    "a=[1,2,3,4]\n",
    "max(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "a6395337",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'3.123'"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 保留小数, round\n",
    "\n",
    "round(3.12348,3)\n",
    "\n",
    "# 格式化输出\n",
    "'{:.3f}'.format(3.12348)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "31372deb",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 取整，大于变量的最小整数：ceil； 小于变量的最大整数，floor\n",
    "import math\n",
    "\n",
    "math.ceil(3.6)\n",
    "math.floor(4.3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "82d24e48",
   "metadata": {},
   "source": [
    "#### 随机函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "74474bec",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.18508838833921104"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import random\n",
    "# random number, uniform~(0,1)\n",
    "random.random()  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "00bb3c42",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "-0.026312134222001637"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#normal distribution  random.gauss(mu,sigma)\n",
    "random.gauss(0,1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "5a4c031d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# set seed; 设置种子   random.seed()\n",
    "random.seed(100)\n",
    "a=random.random()\n",
    "b=random.random()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "8dd4a16e",
   "metadata": {},
   "outputs": [],
   "source": [
    "random.seed(100)\n",
    "a1=random.random()\n",
    "b1=random.random()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "80c963e8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a==a1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "50e149ac",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 从序列中随机取一个数：random.choice()\n",
    "random.choice([1,2,3,4])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "e6b112fc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "7"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#从一个范围内取随机数，random.randrange(start,end,step) 范围：start --- end-1\n",
    "random.randrange(1,11)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "d1200f18",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[7, 1, 3, 6, 4]"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 打乱序列顺序， random.shuffle()  将原序列随机排序\n",
    "a=[1,7,4,6,3]\n",
    "random.shuffle(a)\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "50b92187",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[4, 7, 6]"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 取样本， random.sample(seq., k)\n",
    "random.sample(a,3)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7cfa71e0",
   "metadata": {},
   "source": [
    "#### 常量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "e371995c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3.141592653589793\n",
      "2.718281828459045\n"
     ]
    }
   ],
   "source": [
    "# pi, e \n",
    "import math\n",
    "print(math.pi)\n",
    "print(math.e)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7551bf0f",
   "metadata": {},
   "source": [
    "#### 字符串内建函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "49942eed",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'A'"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#最大，max(str) ; 最小，min(str)\n",
    "\n",
    "str1 = 'ABCabc'\n",
    "min(str1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "7b914556",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'june'"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 转小写 str.lower()； 转大写 str.upper()\n",
    "str1='JUNE'\n",
    "str1.lower()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "1e03c258",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 计算字符串中元素出现的个数 str.count()\n",
    "str1='aaabbe4'\n",
    "str1.count('a')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "7d07ed37",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'AAAbbe4'"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 替换字符串中的元素 str.replace(old,new)\n",
    "str1.replace('aaa','AAA')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "id": "09ffc58d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'20'"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 分拆 str.split()\n",
    "date='2019-11-20'\n",
    "a=date.split('-')[2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "id": "9059f86a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['A', 'log', 'of', 'spaces']"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "line='A log   of spaces'\n",
    "etc=line.split() \n",
    "etc"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "id": "01139d89",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['tingwen', 'uiuc.edu']"
      ]
     },
     "execution_count": 43,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# exercise: a='From tingwen@uiuc.edu  Sat Jan'  获取域名\n",
    "a='From tingwen@uiuc.edu   Sat  Jan'\n",
    "words = a.split()[1]\n",
    "words.split('@')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "f52be68b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Acbdert'"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 首字母大写，str.capitalize()\n",
    "a='acbDert'\n",
    "a.capitalize()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "67c29b92",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'jiij'"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 剔除 str.strip()\n",
    "a='++ jiij++  '\n",
    "#a.strip('+@')\n",
    "a.strip('+ ')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "b56be6d4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 查找字符串中元素的index, \n",
    "# str.find(str, beg=0, end=len(string)), 从左侧开始查找\n",
    "a='abcdeffffffki'\n",
    "a.find('f',6,8)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "725f9c43",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "-1"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# -1 代表找不到！\n",
    "a.find('fa')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "6f57620b",
   "metadata": {},
   "outputs": [
    {
     "ename": "ValueError",
     "evalue": "substring not found",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-15-e2032217c6d5>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[1;31m# 查找: index， str.index(str,beg=0,end=len(string)), BUT 找不打会报错！\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0ma\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mindex\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'fa'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m: substring not found"
     ]
    }
   ],
   "source": [
    "# 查找: index， str.index(str,beg=0,end=len(string)), BUT 找不到会报错！\n",
    "a.index('fa')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": true
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
